<?php
/**
 *
 * 版权所有：安德玛
 * 作    者：安德玛
 * 版本控制：
			20210118----新增推送弹窗！
			20210120----新增邀请新人免费发布任务功能！
			20210128----新增支付成功弹窗控制！
			20210204----新增充值页面点击次数统计功能
			20210206----新增提现按钮点击次数功能
			20210208----新增发布按钮监听功能
 *
 **/
namespace Api\Controller;

class UserController extends ComController
{
    /**
     * 个人中心数据接口
     */
    public function index()
    {
        $s = strtotime(date('Y-m-d').'00:00:00');
        $l = strtotime(date('Y-m-d').'23:59:59');
        //用户信息基本数据
        $user_info = M('user')->where('id='.$this->user['id'])->field('id,username,nickname,head_img,money,money_invite,show_newpay')->find();
        //用户等级信息
        $user_level = M('user_level')->where('id='.$this->user['level_id'])->find();
        $user_info['level_name'] = $user_level['title'];
        $user_info['level_icon'] = C('URL').$user_level['icon'];
        $user_info['is_red'] = $user_level['is_red'];
        $user_info['head_img'] = C('URL').$user_info['head_img'];
        if(strtotime($this->user['expri_day']) < time()){
            $user_info['is_red'] = 0;
        }
        //判断是否到期
        $user_info['is_active'] = 1;
        if(strtotime($this->user['expri_day']) < time()){
            $user_info['is_active'] = 0;
        }
        $user_info['expri_day'] = $this->user['expri_day'];
        //今日收益
        $today_income = M('user_income')->where(array('uid'=>$this->user['id'],'t'=>array('between',array($s,$l))))->sum('money');
        if(!$today_income){
            $today_income = 0;
        }
        $user_info['today_income'] = $today_income;
        /**
         * 我的任务
         */
        //待完成数量
        $task_todo_num = M('user_task')->where(array('status'=>0,'uid'=>$this->user['id']))->count();
        $user_info['task_todo_num'] = $task_todo_num;
        //待审核数量
        $task_audit_num = M('user_task')->where(array('status'=>1,'uid'=>$this->user['id']))->count();
        $user_info['task_audit_num'] = $task_audit_num;
        //已完成数量
        $task_finish_num = M('user_task')->where(array('status'=>2,'uid'=>$this->user['id']))->count();
        $user_info['task_finish_num'] = $task_finish_num;
        //已发布数量
        $task_publish_num = M('task')->where(array('uid'=>$this->user['id'],'pay_status'=>1))->count();
        $user_info['task_publish_num'] = $task_publish_num;
        /**
         * 我的团队
         */
        //当前会员团队等级及推广人数基数
        //当前已推广会员数
        $countSql = "select count(*) as total_num from dz_user a where a.pid='{$this->user['id']}' and a.id in (select b.uid from dz_user_level_buy b where b.`status`=2 group by b.uid)";
        $countQuery = M()->query($countSql);
        $tg_num = $countQuery[0]['total_num'];
        if($this->user['team_level']){
            $team_level = M('team_level')->where(array('name'=>$this->user['team_level']))->find();
            $team_next_level = M('team_level')->where(array('o'=>array('gt',$team_level['o'])))->limit(1)->order('o asc')->select();
            if(empty($team_next_level)){
                $user_info['uprage_num'] = 0;
            }else{
                $next_num = $team_next_level[0]['min_num'];
                $user_info['uprage_num'] = intval($next_num) - intval($tg_num);
            }
        }else{
            $team_next_level = M('team_level')->where(array('o'=>1))->find();
            $user_info['uprage_num'] = intval($team_next_level['min_num']) - intval($tg_num);
        }
        //未读消息数量
        $whereMessage['uid'] = array('in',$this->user['id'].',0');
        $notIdArr = M('user_readmessage')->where(array('uid'=>$this->user['id']))->field('msg_id')->select();
        if($notIdArr){
            $notIds = '';
            foreach($notIdArr as $key=>$vals){
                $notIds.=$vals['msg_id'].',';
            }
            $notIds = rtrim($notIds, ',');
            $whereMessage['id'] = array('not in',$notIds);
        }
        $user_info['noread_notice_num'] = M('user_message')->where($whereMessage)->count();
// 		//增加可提现额度逻辑
// 		$level_name = $user_level['title'];
// 		if($level_name == "普通会员"){
// 			$user_info['money_yes'] = $user_info['money_invite'];
// 		}else{
// 			$user_info['money_yes'] = $user_info['money'] + $user_info['money_invite'];
// 		}
        $this->res['data'] = $user_info;
        $this->response($this->res,'json');
    }
    
    /**
     * 用户信息修改
     */
    public function saveInfo()
    {
        if(!IS_POST){
            $this->res['code'] = 101;
            $this->res['msg'] = '请使用POST方法';
            $this->response($this->res,'json');
        }
        $post_data = file_get_contents('php://input');
        $json = json_decode($post_data);
        $data['nickname'] = $json->nickname;
        if($json->head_img){
            $data['head_img'] = $json->head_img;
        }
        
//         if(!$data['nickname'] or !$data['head_img']){
//             $this->res['code'] = 102;
//             $this->res['msg'] = '昵称或头像存在空项！';
//             $this->response($this->res,'json');
//         }
        $data['update_t'] = time();
		$data['money_yes'] = 
        $res = M('user')->data($data)->where('id='.$this->user['id'])->save();
        if($res){
            $this->res['msg'] = 'success';
            $this->response($this->res,'json');
        }else{
            $this->res['code'] = 500;
            $this->res['msg'] = '';
            $this->response($this->res,'json');
        }
    }
    
    /**
     * 任务佣金明细
     */
    public function taskIncome()
    {
        $p = isset($_GET['p']) ? intval($_GET['p']) : '1';
        $pagesize = isset($_GET['pagesize']) ? intval($_GET['pagesize']) : '10';
        $m = M('user_income');
        $where['type'] = array('in','2,3');
        $where['uid'] = $this->user['id'];
        $offset = $pagesize * ($p - 1);//计算记录偏移量
        $count = $m->where($where)->count();
        $list = $m->where($where)->order('t desc')->limit($offset . ',' . $pagesize)->select();
        foreach ($list as $k=>&$v){
            $list[$k]['t'] = date('Y-m-d H:i:s',$v['t']);
        }
        $page = new \Think\Page($count, $pagesize);
        $page->show();
        $page_arr = array(
            'totalCount'=>intval($count),
            'pageSize'=>$pagesize,
            'totalPage'=>$page->totalPages,
            'currPage'=>intval($p)
        );
        $this->res['data']['page'] = $page_arr;
        $this->res['data']['list'] = $list;
        $this->response($this->res,'json');
    }
    
    /**
     * 推荐奖励明细
     */
    public function tuijianReward()
    {
        $p = isset($_GET['p']) ? intval($_GET['p']) : '1';
        $pagesize = isset($_GET['pagesize']) ? intval($_GET['pagesize']) : '10';
        $m = M('user_income');
        $where['type'] = array('in','4,5');
        $where['uid'] = $this->user['id'];
        $offset = $pagesize * ($p - 1);//计算记录偏移量
        $count = $m->where($where)->count();
        $list = $m->where($where)->order('t desc')->limit($offset . ',' . $pagesize)->select();
        foreach ($list as $k=>&$v){
            $list[$k]['t'] = date('Y-m-d H:i:s',$v['t']);
        }
        $page = new \Think\Page($count, $pagesize);
        $page->show();
        $page_arr = array(
            'totalCount'=>intval($count),
            'pageSize'=>$pagesize,
            'totalPage'=>$page->totalPages,
            'currPage'=>intval($p)
        );
        $this->res['data']['page'] = $page_arr;
        $this->res['data']['list'] = $list;
        $this->response($this->res,'json');
    }
    
    /**
     * 我的团队列表
     */
    public function myTeamList()
    {
        $p = isset($_GET['p']) ? intval($_GET['p']) : '1';
        $pagesize = isset($_GET['pagesize']) ? intval($_GET['pagesize']) : '10';
        $model = M();
        $sqlWhere = "1=1 and ";
        if($this->user['id']){
            $sqlWhere .= "pid=".$this->user['id']." and ";
        }
        $sqlWhere = msubstr($sqlWhere, 0, utf8_strlen($sqlWhere) - 4, "utf-8", false);
        $offset = $pagesize * ($p - 1);//计算记录偏移量
        $count = $model->query("select count(*) as total from 
                                ((select id,username,nickname,t,'1' as level from dz_user where ".$sqlWhere.") 
                                UNION (select id,username,nickname,t,'2' as level from dz_user where pid in 
                                (select id from dz_user where ".$sqlWhere."))) a");
        $count = $count[0]['total'];
        $sql = "(select id,username,nickname,t,'1' as level from dz_user 
                where ".$sqlWhere.") UNION (select id,username,nickname,t,'2' as level 
                from dz_user where pid in (select id from dz_user where ".$sqlWhere.")) 
                order by t desc limit ".$offset . "," . $pagesize;
        $list = $model->query($sql);
        foreach ($list as $k=>&$v){
            $list[$k]['t'] = date('Y-m-d H:i:s',$v['t']);
        }
        $page = new \Think\Page($count, $pagesize);
        $page->show();
        $page_arr = array(
            'totalCount'=>intval($count),
            'pageSize'=>$pagesize,
            'totalPage'=>$page->totalPages,
            'currPage'=>intval($p)
        );
        $this->res['data']['page'] = $page_arr;
        $this->res['data']['list'] = $list;
        $this->response($this->res,'json');
    }
    
    /**
     * 修改密码
     */
    public function updatePwd()
    {
        if(!IS_POST){
            $this->res['code'] = 100;
            $this->res['msg'] = '请用post方法请求接口';
            $this->response($this->res,'json');
        }
        //接收注册表单数据
        $post_data = file_get_contents('php://input');
        $json = json_decode($post_data);
        $code = $json->code;
        $passowrd = $json->password;
        $confirm_pwd = $json->confirm_pwd;
        
        if($code == '' || $passowrd == '' || $confirm_pwd == ''){
            $this->res['code'] = 101;
            $this->res['msg'] = '手机号、验证码、密码及确认密码存在空项';
            $this->response($this->res,'json');
        }
        
        if($passowrd != $confirm_pwd){
            $this->res['code'] = 102;
            $this->res['msg'] = '两次密码输入不一致';
            $this->response($this->res,'json');
        }
        
        $save_code = M('sms_code')->where(array('mobile'=>$this->user['username']))->find();
        if($save_code['expire_t'] < time() || $save_code['code'] != $code){
            $this->res['code'] = 103;
            $this->res['msg'] = '验证码错误';
            $this->response($this->res,'json');
        }
        $res = M('user')->where(array('id'=>$this->user['id']))->data(array('password'=>md5($passowrd),'update_t'=>time()))->save();
        if($res){
            $this->res['msg'] = '新密码设置成功！';
            $this->response($this->res,'json');
        }else{
            $this->res['code'] = 104;
            $this->res['msg'] = '操作失败！';
            $this->response($this->res,'json');
        }
    }
    
    /**
     * 用户退出
     */
    public function logout()
    {	
		$user_info = M('user')->where('id='.$this->user['id'])->field('loginout_num')->find();
		$loginout_num = $user_info['loginout_num'] + 1;
		$data['loginout_num'] = $loginout_num;
		$res1 = M('user')->data($data)->where('id='.$this->user['id'])->save();
        $res = M('user_token')->where(array('token'=>$this->user['token']))->delete();
        if($res){
            $this->res['msg'] = '退出成功';
            $this->response($this->res,'json');
        }else{
            $this->res['msg'] = '退出失败';
            $this->response($this->res,'json');
        } 
    }
	
	
	/**
	     * 用户可用额度保存
	     */
	    public function saveMoney()
	    {
	        if(!IS_POST){
	            $this->res['code'] = 101;
	            $this->res['msg'] = '请使用POST方法';
	            $this->response($this->res,'json');
	        }
	        $post_data = file_get_contents('php://input');
	        $json = json_decode($post_data);
	        $data['money_yes'] = $json->money_yes;
	        
	        $res = M('user')->data($data)->where('id='.$this->user['id'])->save();
	        if($res){
	            $this->res['msg'] = 'success';
	            $this->response($this->res,'json');
	        }else{
	            $this->res['code'] = 500;
	            //$this->res['msg'] = '保存失败，请检查表单项是否合法！';
	            $this->response($this->res,'json');
	        }
	    }
		
		/* 用户邀请新人弹窗查询 */
		public function queryYQ()
		{
		$user_info = M('user')->where('id='.$this->user['id'])->field('show_yq,show_ts,pic')->find();
		
		$this->res['data'] = $user_info;
		$this->response($this->res,'json');
		}
		/* 用户邀请新人弹窗保存*/
		public function saveYQ()
		{
		if(!IS_POST){
		    $this->res['code'] = 101;
		    $this->res['msg'] = '请使用POST方法';
		    $this->response($this->res,'json');
		}
		$post_data = file_get_contents('php://input');
		$json = json_decode($post_data);
		$data['show_yq'] = $json->show_yq;
		
		$res = M('user')->data($data)->where('id='.$this->user['id'])->save();
		if($res){
		    $this->res['msg'] = 'success';
		    $this->response($this->res,'json');
		}else{
		    $this->res['code'] = 500;
		    $this->res['msg'] = '';
		    $this->response($this->res,'json');
		}
		}
		/* 用户邀请新人弹窗保存*/
		public function saveYQ1()
		{
		if(!IS_POST){
		    $this->res['code'] = 101;
		    $this->res['msg'] = '请使用POST方法';
		    $this->response($this->res,'json');
		}
		$post_data = file_get_contents('php://input');
		$json = json_decode($post_data);
		$data['show_ts'] = $json->show_ts;
		
		$res = M('user')->data($data)->where('id='.$this->user['id'])->save();
		if($res){
		    $this->res['msg'] = 'success';
		    $this->response($this->res,'json');
		}else{
		    $this->res['code'] = 500;
		    $this->res['msg'] = '';
		    $this->response($this->res,'json');
		}
		}
		/* 查询登录次数 */
		public function queryTJ()
		{
		$user_info = M('user')->where('id='.$this->user['id'])->field('count')->find();
		
		$this->res['data'] = $user_info;
		$this->response($this->res,'json');
		}
		/*保存登录次数*/
		public function saveTJ()
		{
		if(!IS_POST){
		    $this->res['code'] = 101;
		    $this->res['msg'] = '请使用POST方法';
		    $this->response($this->res,'json');
		}
		$post_data = file_get_contents('php://input');
		$json = json_decode($post_data);
		$data['count'] = $json->count;
		
		$res = M('user')->data($data)->where('id='.$this->user['id'])->save();
		
		//随机生成会员动态
		$tou=array('130','133','135','136','137','138','139',
		           '147','149','150','151','152','153','155',
				   '156','158','159','170','171','173','174',
				   '176','177','178','179','180','181','182',
				   '183','184','185','186','187','189','190',
				   );
		$tou_num=rand(0,35);
		$wei = rand(10000000,99999999);
		$mobile = $tou[$tou_num].$wei;
		$content_t=array('成功邀请好友！','注册成功！','成功获得一级用户推荐奖励！','成功开通VIP会员！','成功发布任务！','成功开通网红！','成功开通钻石VIP！',
		           '成功开通铂金VIP！','成功开通黄金VIP！','成功获得二级任务分佣奖励！','成功获得任务收益！');
		$content_num = rand(0,10);
		$content = $content_t[$content_num];
		M('user_dynamic')->data(array('mobile'=>$mobile,'content'=>$content,'t'=>time()))->add();
		
		if($res){
		    $this->res['msg'] = 'success';
		    $this->response($this->res,'json');
		}else{
		    $this->res['code'] = 500;
		    $this->res['msg'] = '';
		    $this->response($this->res,'json');
		}
		}
		/* 查询邀请人数  */
		public function queryNum()
		{
		$user_info = M('user')->where('id='.$this->user['id'])->field('invite_num')->find();
		
		$this->res['data'] = $user_info;
		$this->response($this->res,'json');
		}
		/* 优惠金额保存*/
		public function savePrice()
		{
		if(!IS_POST){
		    $this->res['code'] = 101;
		    $this->res['msg'] = '请使用POST方法';
		    $this->response($this->res,'json');
		}
		$post_data = file_get_contents('php://input');
		$json = json_decode($post_data);
		$data['price_yh'] = $json->price_yh;
		
		$res = M('user')->data($data)->where('id='.$this->user['id'])->save();
		if($res){
		    $this->res['msg'] = 'success';
		    $this->response($this->res,'json');
		}else{
		    $this->res['code'] = 500;
		    $this->res['msg'] = '';
		    $this->response($this->res,'json');
		}
		}
		/* 查询优惠金额 */
		public function queryPrice()
		{
		$user_info = M('user')->where('id='.$this->user['id'])->field('price_yh')->find();
		
		$this->res['data'] = $user_info;
		$this->response($this->res,'json');
		}
		/* 查询免费发布次数 */
		public function queryFree()
		{
		$user_info = M('user')->where('id='.$this->user['id'])->field('free_num')->find();
		
		$this->res['data'] = $user_info;
		$this->response($this->res,'json');
		}
		/**
		     * 免费发布次数保存
		     */
		    public function saveFree()
		    {
		        if(!IS_POST){
		            $this->res['code'] = 101;
		            $this->res['msg'] = '请使用POST方法';
		            $this->response($this->res,'json');
		        }
		        $post_data = file_get_contents('php://input');
		        $json = json_decode($post_data);
		        $data['free_num'] = $json->free_num;
		        
		        $res = M('user')->data($data)->where('id='.$this->user['id'])->save();
		        if($res){
		            $this->res['msg'] = 'success';
		            $this->response($this->res,'json');
		        }else{
		            $this->res['code'] = 500;
		            //$this->res['msg'] = '保存失败，请检查表单项是否合法！';
		            $this->response($this->res,'json');
		        }
		    }
			/* 用户邀请新人弹窗保存*/
			public function savePay()
			{
			if(!IS_POST){
			    $this->res['code'] = 101;
			    $this->res['msg'] = '请使用POST方法';
			    $this->response($this->res,'json');
			}
			$post_data = file_get_contents('php://input');
			$json = json_decode($post_data);
			$data['show_newpay'] = $json->show_newpay;
			
			$res = M('user')->data($data)->where('id='.$this->user['id'])->save();
			if($res){
			    $this->res['msg'] = 'success';
			    $this->response($this->res,'json');
			}else{
			    $this->res['code'] = 500;
			    $this->res['msg'] = '';
			    $this->response($this->res,'json');
			}
			}
	/* 查询保证金额 */
	public function queryBZJ()
	{
	$bzj_info = M('user_level_buy')->where('uid='.$this->user['id'])->field('money,status')->find();
	if($bzj_info['status'] != 2){
		$bzj_info['money'] = 0;
	}
	$this->res['data'] = $bzj_info;
	$this->response($this->res,'json');
	}
	/* 查询充值点击次数 */
	public function queryMylevel()
	{
	$user_info = M('user')->where('id='.$this->user['id'])->field('mylevel_num')->find();
	
	$this->res['data'] = $user_info;
	$this->response($this->res,'json');
	}
	/* 充值点击次数保存*/
	public function saveMylevel()
	{
	if(!IS_POST){
	    $this->res['code'] = 101;
	    $this->res['msg'] = '请使用POST方法';
	    $this->response($this->res,'json');
	}
	$post_data = file_get_contents('php://input');
	$json = json_decode($post_data);
	$data['mylevel_num'] = $json->mylevel_num;
	
	$res = M('user')->data($data)->where('id='.$this->user['id'])->save();
	if($res){
	    $this->res['msg'] = 'success';
	    $this->response($this->res,'json');
	}else{
	    $this->res['code'] = 500;
	    $this->res['msg'] = '';
	    $this->response($this->res,'json');
	}
	}
	/* 查询提现点击次数 */
	public function queryCash()
	{
	$user_info = M('user')->where('id='.$this->user['id'])->field('cash_num')->find();
	
	$this->res['data'] = $user_info;
	$this->response($this->res,'json');
	}
	/* 提现点击次数保存*/
	public function saveCash()
	{
	if(!IS_POST){
	    $this->res['code'] = 101;
	    $this->res['msg'] = '请使用POST方法';
	    $this->response($this->res,'json');
	}
	$post_data = file_get_contents('php://input');
	$json = json_decode($post_data);
	$data['cash_num'] = $json->cash_num;
	
	$res = M('user')->data($data)->where('id='.$this->user['id'])->save();
	if($res){
	    $this->res['msg'] = 'success';
	    $this->response($this->res,'json');
	}else{
	    $this->res['code'] = 500;
	    $this->res['msg'] = '';
	    $this->response($this->res,'json');
	}
	}
	/* 查询发布点击次数 */
	public function queryFabu()
	{
	$user_info = M('user')->where('id='.$this->user['id'])->field('fabu_num')->find();
	
	$this->res['data'] = $user_info;
	$this->response($this->res,'json');
	}
	/* 发布点击次数保存*/
	public function saveFabu()
	{
	if(!IS_POST){
	    $this->res['code'] = 101;
	    $this->res['msg'] = '请使用POST方法';
	    $this->response($this->res,'json');
	}
	$post_data = file_get_contents('php://input');
	$json = json_decode($post_data);
	$data['fabu_num'] = $json->fabu_num;
	
	$res = M('user')->data($data)->where('id='.$this->user['id'])->save();
	if($res){
	    $this->res['msg'] = 'success';
	    $this->response($this->res,'json');
	}else{
	    $this->res['code'] = 500;
	    $this->res['msg'] = '';
	    $this->response($this->res,'json');
	}
	}
	/* 查询视频源 */
	public function queryVedio()
	{
	$fenlei = 1;
	$list = M('vedios')->where('fenlei='.$fenlei)->select();
	foreach ($list as $k=>&$v){
	    $list[$k]['address'] = C('URL').$v['address'];
	    // if(!$v['url']){
	    //     $list[$k]['url'] = "";
	    // }
		$list[$k]['fengmian'] = C('URL').$v['fengmian'];
	}	
	
	$this->res['data'] = $list;
	$this->response($this->res,'json');
	}
}